package com.anyonavinfo.cpaddemo.service.musicplayerservice;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.anyonavinfo.cpaddemo.Application;
import com.anyonavinfo.cpaddemo.data.musicinfo.MusicInfo;
import com.anyonavinfo.cpaddemo.data.musicinfo.source.MusicInfoDataSource;
import com.anyonavinfo.cpaddemo.data.musicinfo.source.MusicInfoRepository;
import com.anyonavinfo.cpaddemo.utils.ToastManagerUtil;

import java.io.File;
import java.util.List;

import static android.content.Context.AUDIO_SERVICE;

/**
 * Created by zza on 2017/2/6.
 */

public class PlayServiceHelper implements IMusicService{

    private Context mContext;
    private MusicInfoRepository mMusicRepository;
    private List<MusicInfo> mMusicInfoList;
    private AudioManager mAudioManager;
    private MediaPlayer player;
    private boolean isPause=true;
    private boolean isStartPlay;
    private int pausePosition;
    private int currentMusicIndex;
    private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;

    public PlayServiceHelper(MusicInfoRepository musicInfoRepository) {
        this.mMusicRepository = musicInfoRepository;
        mContext=Application.getContextObject();
        initAudioFocusChangeLister();
        loadMusicInfo();
    }

    @Override
    public void play() {
        prepare4Play();
        try {
            player.reset();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if(isStartPlay){
                        next();
                    }
                }
            });
            if (mMusicInfoList.size()>0){
                if (new File(mMusicInfoList.get(currentMusicIndex).getPath()).exists()){
                    player.setDataSource(mMusicInfoList.get(currentMusicIndex).getPath());
                    player.prepare();
                    player.seekTo(pausePosition);
                    isStartPlay = true;
                    int result = mAudioManager.requestAudioFocus(audioFocusChangeListener
                            , AudioManager.STREAM_MUSIC
                            , AudioManager.AUDIOFOCUS_GAIN);
                    if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED != result) {
                        return;
                    }
                    player.start();
                    isPause=false;
                }else {
                    ToastManagerUtil.getInstance().showTextToast(mContext,"音乐不存在，开始播放下一首");
                    play(currentMusicIndex+1);
                }
            }else {
                ToastManagerUtil.getInstance().showTextToast(mContext,"未查找到本地音乐文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // TODO Auto-generated catch block
            //根据情况通知更新UI

        }
    }


    @Override
    public void play(int index) {
        if (index < 0 || index >= mMusicInfoList.size()) {
            index = 0;
        }
        currentMusicIndex = index;
        pausePosition = 0;
        play();
    }

    @Override
    public void pause() {
        isPause=true;
        if (player.isPlaying()) {
            player.pause();
            pausePosition = player.getCurrentPosition();
        }
    }

    @Override
    public void previous() {
        currentMusicIndex--;
        if (currentMusicIndex < 0) {
            currentMusicIndex = mMusicInfoList.size() - 1;
        }
        pausePosition = 0;
        play();
    }

    @Override
    public void next() {
        currentMusicIndex++;
        if (currentMusicIndex >= mMusicInfoList.size()) {
            currentMusicIndex = 0;
        }
        pausePosition = 0;
        play();
    }

    @Override
    public void playRandom() {
        // TODO Auto-generated catch block
        currentMusicIndex= 0;
        pausePosition = 0;
        play();
    }

    @Override
    public int getCurrentPosition() {
        return player.getCurrentPosition();
    }

    @Override
    public void stop() {
        if (player!=null && player.isPlaying()) {
            player.pause();
            player.release();
            player = null;
        }
        mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    }

    @Override
    public boolean isPlaying() {
        if (player!=null){
            return player.isPlaying();
        }
        return false;
    }


    private void initAudioFocusChangeLister() {
        mAudioManager = (AudioManager) mContext.getSystemService(AUDIO_SERVICE);
        player = new MediaPlayer();
        audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                switch (focusChange) {
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        pause();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        if (player != null) {
                            player.setVolume(0.5f, 0.5f);
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN:
                        if (player != null) {
                            player.setVolume(1.0f, 1.0f);
                            if (!player.isPlaying()&&!isPause){
                                play();
                            }
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        pause();
                        break;
                }
            }
        };
    }

    private void loadMusicInfo() {
        mMusicRepository.loadMusicInfo(new MusicInfoDataSource.LoadMusicInfoCallBack() {
            @Override
            public void onMusicInfoLoaded(List<MusicInfo> musicInfoList) {
                mMusicInfoList=musicInfoList;
            }
        });
    }

    private void prepare4Play() {
        if (player == null) {
            player = new MediaPlayer();
        }
        player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
    }

}
